package com.ocm.order.mqListener;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rabbitmq.client.Channel;
import com.ocm.common.constant.OrderStatusConstant;
import com.ocm.core.tool.utils.DateUtil;
import com.ocm.mq.annotation.RabbitAutoAck;
import com.ocm.order.entity.Order;
import com.ocm.order.service.IOrderService;
import com.ocm.pay.to.OrderPayOkTO;
import com.ocm.warehouse.feign.IStockClient;
import com.ocm.warehouse.to.StockUnlockTO;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.ocm.common.constant.OrderStatusConstant.ORDER_STATUS_PAID;
import static com.ocm.common.constant.OrderStatusConstant.ORDER_STATUS_UNPAID;

/**
 * @Author hqy
 * @Date 18/01/2022
 * @Description
 */
@Component
public class OrderListener {

	@Resource
	private IOrderService orderService;

	@Resource
	private IStockClient stockClient;

	@Resource
	private RabbitTemplate rabbitTemplate;

	@RabbitAutoAck
	@RabbitListener(queues = "order.release.order.queue")
	public void orderListen(Long orderId,Channel channel,Message message){
		/**
		 * 查询订单是否被支付
		 */
		if(OrderStatusConstant.ORDER_STATUS_UNPAID==orderService.getOrderStatus(orderId)){
			//未支付 关闭订单
			orderService.update(new UpdateWrapper<Order>().set("status",OrderStatusConstant.ORDER_STATUS_SHUTDOWN).eq("id",orderId));
			//远程调用主动解锁库存
//			R res = stockClient.stockUnLock(orderId);
//			if(!res.isSuccess()){
//				throw new ServiceException(res.getMsg());
//			}
			//发送消息 主动解锁库存
			rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",new StockUnlockTO(orderId));

		}

	}
	@RabbitAutoAck
	@RabbitListener(queues = "order.pay.queue")
	public void orderPayListen(OrderPayOkTO orderPayOkTO, Channel channel, Message message){
		/**
		 * 更改订单为支付成功
		 * 如果订单状态不为待支付 ---> 退款
		 */
		if(!orderService.update(new UpdateWrapper<Order>()
			.set("bank_type",orderPayOkTO.getBankType())
			.set("bank_card",orderPayOkTO.getBankCard())
			.set("pay_time", DateUtil.now())
			.set("status",ORDER_STATUS_PAID)
			.eq("status",ORDER_STATUS_UNPAID)
			.eq("id",orderPayOkTO.getOrderId()))
		){
			orderService.refund(orderPayOkTO.getOrderId(),null);
		}

	}

	/**
	 * 确认收货
	 * @param orderId 订单ID
	 * @param channel 切面需要参数
	 * @param message 切面需要参数
	 */
	@RabbitAutoAck
	@RabbitListener(queues = "received.release.received.queue")
	public void receivedListen(Long orderId,Channel channel,Message message){
		if(OrderStatusConstant.ORDER_STATUS_DELIVER==orderService.getOrderStatus(orderId))
		orderService.receiving(orderId,null);
	}
}
